import { ChangeDetectionStrategy, Component, Inject, OnInit, OnDestroy } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { TopMenu } from 'src/app/shared/components';
import { HomeService, token } from '../../services';
import { Observable, Subscription } from 'rxjs';
import { filter, map } from 'rxjs/operators';

@Component({
  selector: 'app-home-container',
  templateUrl: './home-container.component.html',
  styleUrls: ['./home-container.component.css'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class HomeContainerComponent implements OnInit, OnDestroy {
  selectedTabLink$: Observable<string>;

  constructor(
    private router: Router, 
    private service: HomeService,
    @Inject(token) private baseUrl: string,
    private route: ActivatedRoute
  ) {}

  topMenus$: Observable<TopMenu[]>;
  sub: Subscription
  
  ngOnInit() {
    this.topMenus$ = this.service.getTabs();  
    // 初始化 sub 变量，否则
    this.sub = new Subscription();
    this.selectedTabLink$ = this.route.firstChild.paramMap.pipe(
      filter(params => params.has('tabLink')),
      map(params => params.get('tabLink'))
    )
  }
  
  handleTabSelected(tab: String) {
    let link;
    this.sub = this.topMenus$.subscribe((topMenuList: TopMenu[]) => {
      topMenuList.forEach(item => {
        if(item.title === tab) {
          link = item.link
        }
      });
      this.router.navigate(['home', link])
    });
  }

  ngOnDestroy(): void {
    this.sub.unsubscribe();
  }
}
